<template>
  <div class="mathematical-statistics">
    <a-collapse
      v-if="feaColArray.length > 0 && isSelectedColAllNum && getReady"
      v-model="activeKey"
    >
      <!-- 统计指标 -->
      <a-collapse-panel
        key="stats_index"
        :class="{ disabled_collapse: !getState('stats_index') }"
      >
        <span slot="header">
          统计指标
          <a-tooltip
            v-model="isIconBlueSta"
            overlay-class-name="collapse-tooltip"
            placement="top"
          >
            <template slot="title">
              <span>常用描述性统计指标计算。</span>
            </template>
            <span
              class="annotation-tooltip"
              :style="{ height: '12px', width: '12px' }"
            >
              <a-icon
                type="question-circle"
                :style="{
                  fontSize: '13px',
                  color: isIconBlueSta ? '#6973FF' : 'rgb(200, 200, 200',
                }"
              />
            </span>
          </a-tooltip>
        </span>
        <div class="statistic-card">
          <section
            v-if="getState('stats_index') && isResultExist('stats_index')"
            class="statistic_succeed"
          >
            <div class="statistic-header">结果</div>
            <div class="statistic-content">
              <div class="content_col">
                <div class="content_col_stats_index">
                  求和:
                  <ScientificNotation
                    :statistic="keyResult['stats_index']['sum']"
                  />
                </div>
                <div class="content_col_stats_index">
                  最小值:
                  <ScientificNotation
                    :statistic="keyResult['stats_index']['min']"
                  />
                </div>
              </div>
              <div class="content_col">
                <div class="content_col_stats_index">
                  均值:
                  <ScientificNotation
                    :statistic="keyResult['stats_index']['mean']"
                  />
                </div>
                <div class="content_col_stats_index">
                  最大值:
                  <ScientificNotation
                    :statistic="keyResult['stats_index']['max']"
                  />
                </div>
              </div>
              <div class="content_col">
                <div class="content_col_stats_index">
                  中值:
                  <ScientificNotation
                    :statistic="keyResult['stats_index']['median']"
                  />
                </div>
                <div class="content_col_stats_index">
                  标准差:
                  <ScientificNotation
                    :statistic="keyResult['stats_index']['std']"
                  />
                </div>
              </div>
              <div class="content_col">
                <div class="content_col_stats_index">
                  众数:
                  <ScientificNotation
                    :statistic="keyResult['stats_index']['mode']"
                  />
                </div>
                <div class="content_col_stats_index">
                  95%置信水平:
                  <strongr
                    v-if="
                      keyResult['stats_index']['CI'][0].toString().length > 5
                    "
                  />
                  [
                  <ScientificNotation
                    :statistic="keyResult['stats_index']['CI'][0]"
                  />
                  ,
                  <ScientificNotation
                    :statistic="keyResult['stats_index']['CI'][1]"
                  />
                  ]
                </div>
              </div>
              <div class="content_col">
                <div class="content_col_stats_index">
                  方差:
                  <ScientificNotation
                    :statistic="keyResult['stats_index']['var']"
                  />
                </div>
              </div>
            </div>
          </section>
          <section v-else class="statistic_fail">
            <div class="statistic-content" style="display: flex;">
              <div class="content_fail_icon">
                <img src="@/assets/icon-annotation-fail.svg" />
              </div>
              <div class="content_fail">
                <div
                  v-if="
                    feaColArray.length !== 1 || feaColArrayType[0] === 'varchar'
                  "
                  class="content_fail_col"
                >
                  需要一列数值型
                </div>
                <div v-if="!num_flag" class="content_fail_col">样本数过少</div>
              </div>
            </div>
          </section>
        </div>
      </a-collapse-panel>
      <!-- 正态性检验 -->
      <a-collapse-panel
        key="normal_test"
        :class="{ disabled_collapse: !getState('normal_test') }"
      >
        <span slot="header">
          正态性检验
          <a-tooltip
            v-model="isIconBlueNor"
            overlay-class-name="mathematical-statistic-collapse-tooltip"
            placement="top"
          >
            <template slot="title">
              <span
                >检验是否服从或近似服从正态分布，样本数小于2000时使用Shapiro-Wilk检验，否则使用kolmogorov-smimov检验</span
              >
            </template>
            <span
              class="annotation-tooltip"
              :style="{ height: '12px', width: '12px' }"
            >
              <a-icon
                type="question-circle"
                :style="{
                  fontSize: '13px',
                  color: isIconBlueNor ? '#6973FF' : 'rgb(200, 200, 200',
                }"
              />
            </span>
          </a-tooltip>
        </span>
        <div class="statistic-card">
          <section
            v-if="getState('normal_test') && isResultExist('normal_test')"
            class="statistic_succeed"
          >
            <div class="statistic-content">
              <div
                class="content_col"
                :style="{ 'margin-bottom': '12px', 'margin-top': 0 }"
              >
                零假设：<strong>服从正态分布</strong>
              </div>
            </div>
            <div class="statistic-header">设置</div>
            <div class="statistic-content">
              <div class="content_col">
                显著水平：
                <a-select
                  v-model="alpha_normal_test"
                  default-value="0.05"
                  size="small"
                  :style="{ height: '24px', width: '70px' }"
                  @change="handleChange('normal_test')"
                >
                  <a-select-option value="0.01">0.01</a-select-option>
                  <a-select-option value="0.05">0.05</a-select-option>
                  <a-select-option value="0.1">0.1</a-select-option>
                </a-select>
              </div>
            </div>
            <div class="statistic-header statistic-header-result">结果</div>
            <div class="statistic-content">
              <div class="content_col">
                偏度系数：<strong>{{
                  keyResult['normal_test']['skew']
                }}</strong>
              </div>
              <div class="content_col">
                峰度系数：<strong>{{
                  keyResult['normal_test']['kurtosis']
                }}</strong>
              </div>
              <div class="content_col">
                p值：<strong>{{ keyResult['normal_test']['p'] }}</strong>
              </div>
              <div class="content_col" style="height: 180px;">
                <Chart
                  v-if="hist_chartData != null"
                  :chart-type="'dualAxesChart'"
                  :config="getHistgramData"
                />
              </div>
              <div v-if="pValue > alpha_normal_test" class="content_col">
                <strong>p值 > 显著水平，接受零假设</strong>
              </div>
              <div v-else class="content_col">
                <strong>p值 &lt;= 显著水平，拒绝零假设</strong>
              </div>
              <div
                v-if="pValue <= alpha_normal_test && normal_flag"
                class="content_col_result"
              >
                <strong
                  >但偏度系数和峰度系数的绝对值均&lt;1,故近似服从正态分布</strong
                >
              </div>
            </div>
          </section>
          <section v-else class="statistic_fail">
            <div class="statistic-content" style="display: flex;">
              <div class="content_fail_icon">
                <img src="@/assets/icon-annotation-fail.svg" />
              </div>
              <div class="content_fail">
                <div
                  v-if="
                    feaColArray.length !== 1 || feaColArrayType[0] === 'varchar'
                  "
                  class="content_fail_col"
                >
                  需要一列数值型
                </div>
                <div v-if="!num_flag" class="content_fail_col">样本数过少</div>
              </div>
            </div>
          </section>
        </div>
      </a-collapse-panel>
      <!-- 假设检验 -->
      <a-collapse-panel
        key="arg_test"
        :class="{ disabled_collapse: !getState('arg_test') }"
      >
        <span slot="header">
          假设检验
          <a-tooltip
            v-model="isIconBlueArg"
            overlay-class-name="mathematical-statistic-collapse-tooltip"
            placement="top"
          >
            <template slot="title">
              <span
                >已知总体分布的条件下（服从正态分布）对一些主要的参数(如均值）进行的检验。样本数>=30使用z检验，否则使用t检验。
                t检验分为单样本t检验、配对样本t检验（同一组对象，样本数相同）、两独立样本t检验（不同组对象）。</span
              >
            </template>
            <span
              class="annotation-tooltip"
              :style="{ height: '12px', width: '12px' }"
            >
              <a-icon
                type="question-circle"
                :style="{
                  fontSize: '13px',
                  color: isIconBlueArg ? '#6973FF' : 'rgb(200, 200, 200',
                }"
              />
            </span>
          </a-tooltip>
        </span>
        <div class="statistic-card">
          <section
            v-if="getState('arg_test') && isResultExist('arg_test')"
            class="statistic_succeed"
          >
            <div class="statistic-header">设置</div>
            <div class="statistic-content">
              <section
                v-if="feaColArray.length === 1"
                style="margin-bottom: 12px;"
              >
                <div v-if="fetch_result.num_flag === 2" class="content_col">
                  <strong>使用单样本z检验</strong>
                </div>
                <div v-else class="content_col">
                  <strong>使用单样本t检验</strong>
                </div>
              </section>
              <section v-else>
                <div
                  v-if="fetch_result.num_flag === 2"
                  class="content_col_result"
                  style="margin-bottom: 12px;"
                >
                  <strong>使用双样本z检验</strong>
                </div>
                <div v-else class="content_col_result">
                  <a-radio-group
                    v-model="arg_method"
                    @change="handleChange('arg_test')"
                  >
                    <a-radio :style="selectStyle" value="ind">
                      <strong>使用两独立样本t检验</strong>
                    </a-radio>
                    <a-radio :style="selectStyle" value="rel">
                      <strong>使用配对样本t检验</strong>
                    </a-radio>
                  </a-radio-group>
                </div>
              </section>
              <div class="content_col" style="margin-top: 4px;">
                零假设：
                <span v-if="feaColArray.length === 2">
                  <strong v-if="feaColArray[0].length <= wordMaxLength">{{
                    feaColArray[0]
                  }}</strong>
                  <a-tooltip v-else>
                    <template slot="title">
                      {{ feaColArray[0] }}
                    </template>
                    <strong
                      >{{
                        feaColArray[0].substr(0, wordMaxLength - 1)
                      }}...</strong
                    >
                  </a-tooltip>
                </span>
                <strong>均值</strong>
                <a-select
                  v-model="arg_condition"
                  default-value="="
                  size="small"
                  :style="{
                    height: '24px',
                    width: '70px',
                    'margin-left': '8px',
                    'margin-right': '8px',
                  }"
                  @change="handleChange('arg_test')"
                >
                  <a-select-option value=">">&lt;</a-select-option>
                  <a-select-option value="<">&gt;</a-select-option>
                  <a-select-option value="=">=</a-select-option>
                </a-select>
                <a-input-number
                  v-if="feaColArray.length === 1"
                  id="inputNumber"
                  v-model="arg_observed"
                  size="small"
                  :style="{
                    height: '24px',
                    width: '70px',
                  }"
                  step="0.01"
                  @change="handleChange('arg_test')"
                />
                <span v-else>
                  <strong v-if="feaColArray[1].length <= wordMaxLength">{{
                    feaColArray[1]
                  }}</strong>
                  <a-tooltip v-else>
                    <template slot="title">
                      {{ feaColArray[1] }}
                    </template>
                    <strong
                      >{{
                        feaColArray[1].substr(0, wordMaxLength - 1)
                      }}...</strong
                    >
                  </a-tooltip>
                </span>
                <strong>均值</strong>
              </div>
              <div class="content_col">
                显著水平：
                <a-select
                  v-model="alpha_arg_test"
                  default-value="0.05"
                  size="small"
                  :style="{ height: '24px', width: '70px' }"
                  @change="handleChange('arg_test')"
                >
                  <a-select-option value="0.01">0.01</a-select-option>
                  <a-select-option value="0.05">0.05</a-select-option>
                  <a-select-option value="0.1">0.1</a-select-option>
                </a-select>
              </div>
            </div>
            <div class="statistic-header statistic-header-result">结果</div>
            <div class="statistic-content">
              <!-- <div class="content_col"><strong>总体分布近似服从正态分布，满足假设检验条件</b></div> -->
              <div class="content_col">
                p值：<strong>{{ pValue_arg }}</strong>
              </div>
              <div v-if="pValue_arg > alpha_arg_test" class="content_col">
                <strong>p值 > 显著水平，接受零假设</strong>
              </div>
              <div v-if="pValue_arg <= alpha_arg_test" class="content_col">
                <strong>p值 &lt;= 显著水平，拒绝零假设</strong>
              </div>
            </div>
          </section>
          <section v-else class="statistic_fail">
            <div class="statistic-content" style="display: flex;">
              <div class="content_fail_icon">
                <img src="@/assets/icon-annotation-fail.svg" />
              </div>
              <div class="content_fail">
                <div
                  v-if="
                    feaColArray.length < 1 ||
                    feaColArray.length > 2 ||
                    !isSelectedColAllNum
                  "
                  class="content_fail_col"
                >
                  需要一列或两列数值型
                </div>
                <div v-if="!num_flag" class="content_fail_col">样本数过少</div>
                <div v-if="!normal_flag" class="content_fail_col">
                  总体分布不服从正态分布
                </div>
                <div
                  v-if="feaColArray.length > 1 && !equal_flag"
                  class="content_fail_col"
                >
                  各样本样本数不同
                </div>
              </div>
            </div>
          </section>
        </div>
      </a-collapse-panel>
      <!-- 方差分析 -->
      <a-collapse-panel
        key="var_analysis"
        :class="{ disabled_collapse: !getState('var_analysis') }"
      >
        <span slot="header">
          方差分析
          <a-tooltip
            v-model="isIconBlueVar"
            overlay-class-name="mathematical-statistic-collapse-tooltip"
            placement="top"
          >
            <template slot="title">
              <span
                >判断几组观察到的数据或者处理的结果是否存在显著差异。使用单因素方差分析。
                各样本须是相互独立的随机样本，各样本分布服从正态分布，满足方差齐性（使用Levene检验）的条件。</span
              >
            </template>
            <span
              class="annotation-tooltip"
              :style="{ height: '12px', width: '12px' }"
            >
              <a-icon
                type="question-circle"
                :style="{
                  fontSize: '13px',
                  color: isIconBlueVar ? '#6973FF' : 'rgb(200, 200, 200',
                }"
              />
            </span>
          </a-tooltip>
        </span>
        <div class="statistic-card">
          <section
            v-if="getState('var_analysis') && isResultExist('var_analysis')"
            class="statistic_succeed"
          >
            <div class="statistic-content">
              <div
                class="content_col"
                :style="{ 'margin-bottom': '12px', 'margin-top': 0 }"
              >
                零假设：<strong>各样本不存在显著差异</strong>
              </div>
            </div>
            <div class="statistic-header">设置</div>
            <div class="statistic-content">
              <div class="content_col">
                显著水平：
                <a-select
                  v-model="alpha_var_analysis"
                  default-value="0.05"
                  size="small"
                  :style="{ height: '24px', width: '70px' }"
                  @change="handleChange('var_analysis')"
                >
                  <a-select-option value="0.01">0.01</a-select-option>
                  <a-select-option value="0.05">0.05</a-select-option>
                  <a-select-option value="0.1">0.1</a-select-option>
                </a-select>
              </div>
            </div>
            <div class="statistic-header statistic-header-result">结果</div>
            <div class="statistic-content">
              <div class="content_col">
                p值：<strong>{{ pValue_arg }}</strong>
              </div>
              <div v-if="pValue_var > alpha_var_analysis" class="content_col">
                <strong>p值 > 显著水平，接受零假设</strong>
              </div>
              <div v-if="pValue_var <= alpha_var_analysis" class="content_col">
                <strong>p值 &lt;= 显著水平，拒绝零假设</strong>
              </div>
            </div>
          </section>
          <section v-else class="statistic_fail">
            <div class="statistic-content" style="display: flex;">
              <div class="content_fail_icon">
                <img src="@/assets/icon-annotation-fail.svg" />
              </div>
              <div class="content_fail">
                <div
                  v-if="feaColArray.length < 2 || !isSelectedColAllNum"
                  class="content_fail_col"
                >
                  需要两列或两列以上数值型
                </div>
                <div v-if="!num_flag" class="content_fail_col">样本数过少</div>
                <div v-if="!normal_flag" class="content_fail_col">
                  总体分布不服从正态分布
                </div>
                <div v-if="!levene_flag" class="content_fail_col">
                  总体分布不服从方差齐性
                </div>
              </div>
            </div>
          </section>
        </div>
      </a-collapse-panel>
      <!-- 信度分析 -->
      <a-collapse-panel
        key="reliability_analysis"
        :class="{ disabled_collapse: !getState('reliability_analysis') }"
      >
        <span slot="header">
          信度分析
          <a-tooltip
            v-model="isIconBlueRel"
            overlay-class-name="mathematical-statistic-collapse-tooltip"
            placement="top"
          >
            <template slot="title">
              <span
                >采用同样的方法对同一对象重复测量时所得结果的一致性程度。使用Cronbach's
                alpha信度系数。</span
              >
            </template>
            <span
              class="annotation-tooltip"
              :style="{ height: '12px', width: '12px' }"
            >
              <a-icon
                type="question-circle"
                :style="{
                  fontSize: '13px',
                  color: isIconBlueRel ? '#6973FF' : 'rgb(200, 200, 200',
                }"
              />
            </span>
          </a-tooltip>
        </span>
        <div class="statistic-card">
          <section
            v-if="
              getState('reliability_analysis') &&
              isResultExist('reliability_analysis')
            "
            class="statistic_succeed"
          >
            <div class="statistic-header">结果</div>
            <div class="statistic-content">
              <div class="content_col">
                Cronbach's alpha系数:
                <strong>{{ keyResult.reliability_analysis }}</strong>
              </div>
              <div
                v-if="keyResult.reliability_analysis >= 0.9"
                class="content_col"
              >
                评价：<strong>非常理想</strong>
              </div>
              <div
                v-else-if="keyResult.reliability_analysis >= 0.8"
                class="content_col"
              >
                评价：<strong>甚佳</strong>
              </div>
              <div
                v-else-if="keyResult.reliability_analysis >= 0.7"
                class="content_col"
              >
                评价：<strong>佳</strong>
              </div>
              <div
                v-else-if="keyResult.reliability_analysis >= 0.6"
                class="content_col"
              >
                评价：<strong>尚可</strong>
              </div>
              <div
                v-else-if="keyResult.reliability_analysis >= 0.5"
                class="content_col"
              >
                评价：<strong>可信偏低</strong>
              </div>
              <div v-else class="content_col">
                评价：<strong>欠佳最好剔除</strong>
              </div>
            </div>
          </section>
          <section v-else class="statistic_fail">
            <div class="statistic-content" style="display: flex;">
              <div class="content_fail_icon">
                <img src="@/assets/icon-annotation-fail.svg" />
              </div>
              <div class="content_fail">
                <div
                  v-if="feaColArray.length < 2 || !isSelectedColAllNum"
                  class="content_fail_col"
                >
                  需要两列或两列以上数值型
                </div>
                <div v-if="!num_flag" class="content_fail_col">样本数过少</div>
                <div
                  v-if="feaColArray.length > 1 && !equal_flag"
                  class="content_fail_col"
                >
                  各样本样本数不同
                </div>
              </div>
            </div>
          </section>
        </div>
      </a-collapse-panel>
      <!-- 相关分析 -->
      <a-collapse-panel
        key="corr_analysis"
        :class="{ disabled_collapse: !getState('corr_analysis') }"
      >
        <span slot="header">
          相关分析
          <a-tooltip
            v-model="isIconBlueCor"
            overlay-class-name="mathematical-statistic-collapse-tooltip"
            placement="top"
          >
            <template slot="title">
              <span
                >研究两个或多个变量之间是否存在某种依存关系。正态分布样本使用Pearson相关系数，非正态分布样本使用Spearman相关系数。</span
              >
            </template>
            <span
              class="annotation-tooltip"
              :style="{ height: '12px', width: '12px' }"
            >
              <a-icon
                type="question-circle"
                :style="{
                  fontSize: '13px',
                  color: isIconBlueCor ? '#6973FF' : 'rgb(200, 200, 200',
                }"
              />
            </span>
          </a-tooltip>
        </span>
        <div class="statistic-card">
          <section
            v-if="getState('corr_analysis') && isResultExist('corr_analysis')"
            class="statistic_succeed"
          >
            <div class="statistic-header">结果</div>
            <div class="statistic-content" style="height: 180px;">
              <Chart
                v-if="corr_chartData != null"
                :chart-type="'heatmapMatrix'"
                :config="getHeatMapData"
              />
            </div>
          </section>
          <section v-else class="statistic_fail">
            <div class="statistic-content" style="display: flex;">
              <div class="content_fail_icon">
                <img src="@/assets/icon-annotation-fail.svg" />
              </div>
              <div class="content_fail">
                <div
                  v-if="feaColArray.length < 2 || !isSelectedColAllNum"
                  class="content_fail_col"
                >
                  需要两列或两列以上数值型
                </div>
                <div v-if="!num_flag" class="content_fail_col">样本数过少</div>
                <div
                  v-if="feaColArray.length > 1 && !equal_flag"
                  class="content_fail_col"
                >
                  各样本样本数不同
                </div>
              </div>
            </div>
          </section>
        </div>
      </a-collapse-panel>
    </a-collapse>
    <div
      v-else-if="isSelectedColAllNum && feaColArray.length > 0 && isLoading"
      class="spinner-mask"
    >
      <a-spin class="spinner" :spinning="isSelectedColAllNum && isLoading" />
    </div>
    <div v-else class="empty-status-container">
      <img class="empty-img" :src="publicPath + '/img/empty.svg'" />
      <span v-if="isSelectedColAllNum">暂无数理统计推荐</span>
      <span v-else>需要数值型数据</span>
    </div>
  </div>
</template>
<script lang="ts">
import { Component, Watch, Vue } from 'vue-property-decorator'
import { computeStats } from '@/api/mathematical-statistics'
import DataViewStore from '@/store/modules/dataview'
import { isEmpty, isNumber, cloneDeep } from 'lodash'
import { publicPath } from '@/api/constants'
import Chart from '@/components/chart/chart.vue'
import Big from 'big.js'
import ScientificNotation from './ScientificNotation.vue'

interface ParameterInterface {
  [key: string]: any
}

@Component({
  components: {
    Chart,
    ScientificNotation,
  },
})
export default class MathematicalStatistics extends Vue {
  private activeKey: string[] = []
  private activeKeyPreLen = 0
  private getReady: boolean = false
  private isLoading: boolean = false
  private statsMaxLength: number = 5
  private wordMaxLength: number = 4
  private isIconBlueSta: boolean = false
  private isIconBlueNor: boolean = false
  private isIconBlueArg: boolean = false
  private isIconBlueVar: boolean = false
  private isIconBlueRel: boolean = false
  private isIconBlueCor: boolean = false
  private publicPath = publicPath

  // 是否已选中某个节点
  private get hasSelectedNode() {
    return !!DataViewStore.selectNode
  }

  // 一些基本的配置参数
  private selectStyle = {
    display: 'block',
    height: '20px',
    lineHeight: '20px',
    'margin-bottom': '10px',
    'font-size': '14px',
    'font-weight': 400,
    color: '#373B52',
    'letter-spacing': '1px',
  }
  private typeParameterDefalue: ParameterInterface = {
    stats_index: {},
    normal_test: {
      alpha: 0.05,
    },
    arg_test: {
      method: 'ind',
      condition: '>',
      observed: 0,
      alpha: 0.05,
    },
    var_analysis: {
      alpha: 0.05,
    },
    reliability_analysis: {},
    corr_analysis: {},
    levene_test: {},
  }

  // 储存后端数据
  private keyStatus: ParameterInterface = {
    stats_index: false,
    normal_test: false,
    arg_test: false,
    var_analysis: false,
    reliability_analysis: false,
    corr_analysis: false,
    blank: false,
  }
  private fetch_result: any = null
  private keyResult: ParameterInterface = {
    stats_index: null,
    normal_test: null,
    arg_test: null,
    var_analysis: null,
    reliability_analysis: null,
    corr_analysis: null,
  }
  private keysArray = [
    'stats_index',
    'normal_test',
    'arg_test',
    'var_analysis',
    'reliability_analysis',
    'corr_analysis',
  ]
  private normal_flag: boolean = false
  private levene_flag: boolean = false
  private num_flag: boolean = false
  private equal_flag: boolean = false
  private pValue: number = 0
  private pValue_arg: number = 0
  private pValue_var: number = 0
  private isSelectedColAllNum: boolean = true

  // chart数据
  private corr_chartData: any = null
  private hist_chartData: any = null

  // 可选参数
  private arg_condition: string = '='
  private arg_observed: number = 0
  private alpha_normal_test: number = 0.05
  private alpha_arg_test: number = 0.05
  private alpha_var_analysis: number = 0.05
  private arg_method: string = 'ind'

  /**
   * 初始化
   */
  created() {
    const results = DataViewStore.selectedColumns.map((item) => {
      return item.desc
    })
    const resultSet = new Set(results)
    this.isSelectedColAllNum =
      !resultSet.has('varchar') && !resultSet.has('text')
    this.getReady = false
    this.getFlags()
  }

  /**
   * 内容折叠
   * 若是打开动作 则向后端要对应的数据
   */
  @Watch('activeKey', { deep: true })
  public onActiveKeyChange(newValue: any) {
    // 判断是否是打开动作，关闭动作不操作
    // if(newValue.length > this.activeKeyPreLen) {
    //   const key: string = newValue[newValue.length - 1]
    //   const parameters = this.getParameters(key, this.typeParameterDefalue[key])

    //   // 判断状态，防止重复发送请求
    //   if(!this.keyStatus[key]) {
    //     this.keyStatus[key] = true
    //     this.queryStatistic(parameters)
    //   }
    // }
    this.activeKeyPreLen = newValue.length
  }

  /**
   * 监视数据集选择的列的变化
   * 将所有的数据恢复到原始状态，重新初始化
   */
  @Watch('feaColArray', { deep: true })
  public onColChange() {
    this.activeKey = []
    this.arg_condition = '='
    this.arg_observed = 0
    this.alpha_normal_test = 0.05
    this.alpha_arg_test = 0.05
    this.alpha_var_analysis = 0.05
    this.corr_chartData = null
    this.hist_chartData = null
    this.keyStatus = {
      stats_index: false,
      normal_test: false,
      arg_test: false,
      var_analysis: false,
      reliability_analysis: false,
      corr_analysis: false,
      blank: false,
    }

    const results = DataViewStore.selectedColumns.map((item) => {
      return item.desc
    })
    const resultSet = new Set(results)
    this.isSelectedColAllNum =
      !resultSet.has('varchar') && !resultSet.has('text')
    this.getReady = false

    // 在选中的列大于0且其中不包含非数值型数据时，获取后端数据
    if (results.length > 0 && this.isSelectedColAllNum) {
      this.getFlags()
    }
  }

  /**
   * 获取数据集选择的列
   */
  private get feaColArray() {
    return DataViewStore.selectedColumns.map((item) => {
      return item.name
    })
  }

  /**
   * 获取列类型
   * 判断是否是数值型
   */
  private get feaColArrayType() {
    const result = DataViewStore.selectedColumns.map((item) => {
      return item.desc
    })
    this.isSelectedColAllNum =
      !result.includes('varchar') && !result.includes('text')
    return result
  }

  /**
   * 更新flag状态 用于判断抽屉是否需要置灰
   * 向后端拿数据
   */
  private getFlags() {
    const parameters = this.getParameters('', {})
    // 判断状态，防止重复发送请求
    if (!this.keyStatus.blank) {
      this.keyStatus.blank = true
      this.queryStatistic(parameters)
    }
  }

  /**
   *  获取post请求所需参数
   *  @param type 数据类型
   *  @param dataPara 类型所需非默认参数
   */
  public getParameters(type: string, dataPara: any) {
    // 必选参数
    let tableName = DataViewStore.selectNodeTableInfo?.tableName
    if (DataViewStore.selectNode && DataViewStore.selectNode.type === 3) {
      tableName = `dataset.${tableName}`
    }
    const featureColArray = DataViewStore.selectedColumns.map((item) => {
      return item.name
    })
    const featureCol = featureColArray.join(',')
    const result = {
      tableNames: tableName,
      data: dataPara,
    }
    result.data.func = type
    result.data.featureCol = featureCol
    return result
  }

  /**
   * 获取详细参数数据
   * @param type 数据类型
   */
  private getDetailParameters(type: string) {
    switch (type) {
      case 'normal_test':
        return { alpha: this.alpha_normal_test }
      case 'arg_test':
        return {
          method: this.arg_method,
          condition: this.arg_condition,
          observed: this.arg_observed,
          alpha: this.alpha_arg_test,
        }
      case 'var_analysis':
        return { alpha: this.alpha_var_analysis }
      default:
        return {}
    }
  }

  /**
   * 获取词条状态，判断词条是否满足条件
   * @param type 数据类型
   */
  private getState(type: string) {
    let result = true
    if (this.fetch_result === null) {
      return false
    }
    if (type === 'stats_index' || type === 'normal_test') {
      result =
        this.feaColArray.length === 1 &&
        this.num_flag &&
        this.feaColArrayType[0] !== 'varchar'
    } else if (type === 'arg_test') {
      result =
        (this.feaColArray.length === 1 || this.feaColArray.length === 2) &&
        this.isSelectedColAllNum &&
        this.num_flag &&
        this.normal_flag
      // 最后一行判断条件
      // 小样本在选两列时需要满足equal_flag
      if (this.feaColArray.length === 2 && this.fetch_result.num_flag === 1) {
        result = result && this.equal_flag
      }
    } else if (type === 'var_analysis') {
      result =
        this.feaColArray.length > 1 &&
        this.isSelectedColAllNum &&
        this.num_flag &&
        this.normal_flag &&
        this.levene_flag
    } else if (type === 'reliability_analysis') {
      result = this.feaColArray.length > 1 && this.num_flag && this.equal_flag
    } else if (type === 'corr_analysis') {
      result = this.feaColArray.length > 1 && this.num_flag && this.equal_flag
    }
    return result
  }

  /**
   * 向后端发送请求并作出处理
   * @param options
   */
  public async queryStatistic(options: any) {
    if (!this.hasSelectedNode) {
      return
    }

    this.keyStatus[options.data.func] = true
    if (options.data.func === '') {
      this.isLoading = true
    }
    const response = await computeStats({
      data: options,
    })

    // 如果成功
    if (
      response.status === 200 &&
      response.data.code === 100 &&
      response.data.result.feature_col &&
      this.isResultColSelect(response.data.result.feature_col)
    ) {
      this.fetch_result = response.data.result
      // 把数据储存到组件中
      /* eslint-disable @typescript-eslint/dot-notation */
      if (options.data.func !== '') {
        this.keyResult[options.data.func] =
          response.data.result[options.data.func]
        this.keyStatus[options.data.func] = false
      } else {
        this.keyStatus.blank = false
        this.keysArray.forEach((key: string) => {
          if (
            response.data.result[key] !== undefined ||
            response.data.result[key] != null
          ) {
            this.keyResult[key] = response.data.result[key]
            this.keyStatus[key] = false
            // 处理chart数据
            this.prepareChart(key)
          }
        })
      }
      if (response.data.result) {
        if (response.data.result['normal_flag'] !== undefined) {
          this.normal_flag = response.data.result['normal_flag']
        }
        if (response.data.result['levene_flag'] !== undefined) {
          this.levene_flag = response.data.result['levene_flag']
        }
        if (response.data.result['num_flag'] !== undefined) {
          this.num_flag = response.data.result['num_flag']
        }
        if (response.data.result['equal_flag'] !== undefined) {
          this.equal_flag = response.data.result['equal_flag']
        }
        if (response.data.result['normal_test'] !== undefined) {
          this.pValue = response.data.result['normal_test']['p']
        }
        if (response.data.result['arg_test'] !== undefined) {
          this.pValue_arg = response.data.result['arg_test']
        }
        if (response.data.result['var_analysis'] !== undefined) {
          this.pValue_var = response.data.result['var_analysis']
        }

        // 处理chart数据
        this.prepareChart(options.data.func)

        // 更新状态
        this.getReady = true
        this.isLoading = false
      }
    }
  }

  /**
   * 判断当前返回的数据是否是选中的数据
   */
  public isResultColSelect(cols: string) {
    const colNames = cols.split(',')
    if (colNames.length !== this.feaColArray.length) {
      return false
    }
    let result = true
    colNames.forEach((col: string) => {
      if (!this.feaColArray.includes(col)) {
        result = false
      }
    })
    return result
  }

  /**
   * 数据是否有后端可用返回值
   * @param type 数据类型
   */
  public isResultExist(type: string) {
    const result = this.keyResult[type]
    return isNumber(result) || (result !== null && !isEmpty(result))
  }

  /**
   * 检验值改变，需要重新获取后端数据
   */
  public handleChange(key: string) {
    const parameters = this.getParameters(key, this.getDetailParameters(key))

    this.keyStatus[key] = true
    this.queryStatistic(parameters)
  }

  /**
   * 图表数据准备
   * @param key 数据类型
   */
  private prepareChart(key: string) {
    // 直方图数据处理 && 热力矩阵图数据处理
    if (key === 'normal_test') {
      const data: any = this.fetch_result
      const result: any[] = []
      data.bin.forEach((item: any, i: number) => {
        result.push({
          type: `${item}`,
          value1: data.hist[i],
          value2: data.normal[i],
        })
      })
      this.hist_chartData = result
    } else if (key === 'corr_analysis') {
      // const min = Math.min(...this.keyResult.corr_analysis)
      const data = cloneDeep(this.keyResult.corr_analysis)
      // if (min < 0) {
      //   data = data.map((item: number) => {
      //     return item - min
      //   })
      // }
      let index = 0
      const result: any[] = []
      this.feaColArray.forEach((itemy: any) => {
        this.feaColArray.forEach((itemx: any) => {
          result.push({
            x: itemx,
            y: itemy,
            value: data[index],
          })
          index += 1
        })
      })
      this.corr_chartData = result
    }
  }

  /**
   * 获取相关矩阵热力图数据
   */
  private get getHeatMapData() {
    return {
      titleIsShow: false,
      value: this.corr_chartData,
      valueKey: 'y',
      labelKey: 'x',
      heatMapDataKey: 'value',
      labelIsShow: true,
      labelTextMaxLength: 3,
      size: [354, 176],
      padding: [10, 10, 10, 10],
      legendBasicColor: ['#D6E4FF', '#597EF7'],
      xAxisFontSize: 12,
      xAxisLabelMaxLength: 5,
      yAxisFontSize: 12,
      yAxisLabelMaxLength: 5,
    }
  }

  /**
   * 获取直方图数据
   */
  private get getHistgramData() {
    return {
      titleIsShow: false,
      value: [this.hist_chartData, this.hist_chartData],
      valueKey: ['value1', 'value2'],
      labelKey: 'type',
      xAxisAttribute: 'type',
      yAxisAttribute: [['value1'], ['value2']],
      size: [354, 176],
      padding: [10, 0, 10, 0],
      xAxisLabelMaxLength: 5,
      geometryOptions: [
        {
          geometry: 'column',
          minColumnWidth: 22,
          maxColumnWidth: 22,
          color: 'rgba(91,143,249,0.85)',
          label: { position: 'middle', style: { fill: '#6D7278' } },
        },
        { geometry: 'line', smooth: true, color: '#6D7278' },
      ],
      legendIsShow: false,
      tooltipIsShow: false,
      colors: '#rgba(91,143,249,0.85)',
      // axis: {
      //   value1: {
      //     title: {text: 'aaa'}
      //   }
      // }
    }
  }

  /**
   * 对统计指标的数据处理
   * 如果数据特别长返回科学记数法的数据，其他返回原数据
   * @param bignum 需要处理的数据
   */
  private getNum(bignum: number) {
    const result = new Big(bignum)
    return bignum.toString().length > 5 ? result.toExponential(2) : bignum
  }
}
</script>

<style lang="less" scoped>
.mathematical-statistics {
  height: 100%;
  margin: auto;
  overflow-y: scroll;
  width: 420px;

  /deep/ .ant-collapse {
    border: 1px solid rgba(88, 98, 230, 0.15);
    border-radius: 4px;
    box-shadow: 0 1px 5px 0 rgba(88, 98, 230, 0.15);

    .ant-collapse-item {
      border-bottom: 0 solid #fff;

      .ant-collapse-header {
        background: #fff;
        color: #373b52;
        font-size: 16px;
        font-weight: 600;
        height: 50px;
        letter-spacing: 1px;
      }

      .ant-collapse-header:hover {
        background: rgba(103, 113, 252, 0.1);
      }

      .ant-collapse-content {
        background: #fafafc;
        border-bottom: 1px solid rgba(88, 98, 230, 0.15);
        border-top: 0 solid #fff;
        padding: 12px 32px 14px;
        width: 100%;

        .ant-collapse-content-box {
          padding: 0;
        }
      }
    }

    .ant-collapse-item-active {
      .ant-collapse-header {
        color: #6973ff;
      }
    }

    .disabled_collapse {
      .ant-collapse-header {
        color: rgb(200, 200, 200);
      }
    }
  }

  .statistic-header {
    color: #373b52;
    font-size: 14px;
    font-weight: 600;
    height: 20px;
    letter-spacing: 1px;
    line-height: 20px;
  }

  .statistic-header-result {
    margin-top: 12px;
  }

  .statistic-content {
    position: relative;

    .content_col {
      color: #5d637e;
      display: flex;
      font-size: 14px;
      font-weight: 400;
      height: 20px;
      letter-spacing: 1px;
      line-height: 20px;
      margin-top: 12px;

      .content_col_stats_index:nth-child(odd) {
        width: 131px;
      }
    }

    .content_col_result {
      color: #5d637e;
      font-size: 14px;
      font-weight: 400;
      letter-spacing: 1px;
      line-height: 20px;
      margin-top: 12px;
    }

    .content_fail_icon {
      margin-right: 12px;
    }

    .content_fail {
      color: #5d637e;
      font-size: 14px;
      font-weight: 400;
      letter-spacing: 1px;

      .content_fail_col {
        height: 20px;
        line-height: 20px;
        margin-bottom: 8px;
      }
    }
  }

  .empty-status-container {
    align-items: center;
    display: flex;
    flex-direction: column;
    height: 100%;
    justify-content: center;

    .empty-img {
      margin-bottom: 15px;
      margin-top: 200px;
    }
  }

  .spinner-mask {
    align-items: center;
    display: flex;
    height: 100%;
    justify-content: center;
    z-index: 1002;
  }
}

.mathematical-statistics::-webkit-scrollbar {
  width: 0 !important;
}
</style>
<style lang="less">
.mathematical-statistic-collapse-tooltip {
  /deep/ .ant-tooltip-inner {
    text-indent: 25px;
  }
}
</style>
